﻿using System;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic; 
using System.Data;
using TimeTravel.Commons;
using TimeTravel.Extentions;
using TimeTravel.IData;
using TimeTravel.Components;

namespace TimeTravel.SqlServer  
{
    public  class ManageLogData : IManageLogData
    {
        #region Fields

        private static readonly SqlHelper DbHelper = new SqlHelper();
        private static readonly string[] V_Columns = { "[id]", "[loginip]", "[date]", "[body]","[userid]","[username]","[nickname]","[userpicture]","[useremail]" };

        #endregion

        #region Implementation of IDataBase<ManageLogInfo>

        /// <summary>
        /// 添加记录
        /// </summary>
        public int Add(ManageLogInfo manageLog)
        {
            if (manageLog == null) return 0;
            var strSql = new StringBuilder();
            strSql.Append("insert into ManageLog (");
            strSql.Append("[loginip],[date],[body],[userid] ) ");
            strSql.Append(" values ");
            strSql.Append("(@loginip,@date,@body,@userid) ;");
            strSql.Append("select @@IDENTITY;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@loginip", SqlDbType.NVarChar, 50),
                                            new SqlParameter("@date", SqlDbType.Int),
                                            new SqlParameter("@body", SqlDbType.NVarChar, 100),
                                            new SqlParameter("@userid", SqlDbType.Int)
                                        };
            parameters[0].Value = manageLog.LoginIP;
            parameters[1].Value = manageLog.Date;
            parameters[2].Value = manageLog.Body;
            parameters[3].Value = manageLog.User.ID;
            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString(), parameters);
            return result == null ? 0 : Convert.ToInt32(result);
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="id"></param>
        [Obsolete("该方法未实现")]
        public void Delete(int id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 更新记录（未实现）
        /// </summary>
        /// <param name="manageLog"></param>
        [Obsolete("该方法未实现")]
        public void Update(ManageLogInfo manageLog)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public IList<ManageLogInfo> GetAll()
        {
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from V_ManageLog ", String.Join(",", V_Columns));
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteObjectList(strSql.ToString(), DataReaderParser);
            return result.ToList();
        }

        /// <summary>
        /// 根据条件获取
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RecordSet<ManageLogInfo> GetBySearch(PageQueryInfo query)
        {
            if(query == null) return new RecordSet<ManageLogInfo>();
            return DbHelper.ExecutePaging("V_ManageLog", query, DataReaderParser, V_Columns);
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ManageLogInfo GetOne(int id)
        {
            if (id == 0) return null;
            var strSql = new StringBuilder();
            strSql.AppendFormat("select {0} from V_ManageLog ", String.Join(",", V_Columns));
            strSql.Append("where [id] = @id;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@id", SqlDbType.Int)
                                        };
            parameters[0].Value = id;
            return DbHelper.ExecuteObject(CommandType.Text, strSql.ToString(), DataReaderParser, parameters);
        }

        /// <summary>
        /// 删除指定时间段内日志
        /// </summary>
        /// <param name="start">开始时间（时间戳格式）</param>
        /// <param name="end">结束时间（时间戳格式）</param>
        public void DeleteBatch(int start, int end)
        {
            if (start >= end) return;
            var strSql = new StringBuilder();
            strSql.Append("update ManageLog set DeleteFlag = 1 ");
            strSql.Append("where date>=@start and date<=@end and DeleteFlag = 0;");
            SqlParameter[] parameters = {
                                            new SqlParameter("@start", SqlDbType.Int),
                                            new SqlParameter("@end", SqlDbType.Int)
                                        };
            parameters[0].Value = start;
            parameters[1].Value = end;
            DbHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), parameters);
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns></returns>
        public int GetTotalCount()
        {
            var strSql = new StringBuilder();
            strSql.Append("select count(id) from ManageLog ");
            strSql.Append("where DeleteFlag = 0;");
            var result = DbHelper.ExecuteScalar(CommandType.Text, strSql.ToString());
            return result == null ? 0 : Convert.ToInt32(result);
        }

        #endregion

        #region BuildNavMenuObject

        /// <summary>
        /// 从DataReader中构建对象
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private ManageLogInfo DataReaderParser(IDataReader reader)
        {
            var manageLog = new ManageLogInfo
                                {
                                    ID = reader.GetInt32("id"),
                                    LoginIP = reader.GetString("loginip"),
                                    Body = reader.GetString("body"),
                                    Date = reader.GetInt32("date")
                                };

            var sysUser = new SysUserInfo
            {
                ID = reader.GetInt32("userid"),
                Name = reader.GetString("username"),
                NickName = reader.GetString("nickname"),
                Picture = reader.GetString("userpicture"),
                Email = reader.GetString("useremail")
            };
            manageLog.User = sysUser;
            return manageLog;
        }

        #endregion
    }
}

